package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.enums.BoardStatus;
import com.example.forum.common.enums.ResultCode;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Board;
import com.example.forum.services.IBoardService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hanzishuai
 * @date 2025/4/9 17:20
 * @Description 板块接口
 */
@Slf4j
@Tag(name = "板块接口")
@RestController
@RequestMapping("/board")
public class BoardController {

    // 从配置帖子中读取 num，如果没有配置，默认为 9
    @Value("${forum.index.board-num:9}")
    private Integer indexBoardNum;

    @Resource
    private IBoardService boardService;



    /**
     * Created by hanzishuai on 2025/4/9
     *
     * @param
     * @return com.example.forum.common.AppResult<java.util.List < com.example.forum.model.Board>>
     * @Description 查询首页板块列表
     */
    @Operation(summary = "获取首页板块列表")
    @GetMapping("/topList")
    public AppResult<List<Board>> topList() {
        log.info("配置首页板块个数为：{}", indexBoardNum);

        // 查询结果
        List<Board> boards = boardService.selectByNum(indexBoardNum);

        // 判断是否为空
        if (boards == null) {
            boards = new ArrayList<>();
        }


        return AppResult.success(boards);
    }


    /**
     * Created by hanzishuai on 2025/4/10
     *
     * @param id 板块 Id
     * @return com.example.forum.common.AppResult<com.example.forum.model.Board>
     * @Description  根据板块 Id 得到板块信息
     */
    @Operation(summary = "根据板块 Id 得到板块信息")
    @GetMapping("/getInfoById")
    public AppResult<Board> getInfoById(@Parameter(description = "板块 Id") @RequestParam("id") @NonNull Long id) {

        Board board = boardService.selectById(id);
        // 校验
        if(board == null || board.getDeleteState() == BoardStatus.IS_DELETE.getStatus()) {
            log.warn("{}", ResultCode.FAILED_BOARD_NOT_EXISTS);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        return AppResult.success(board);
    }
}































